package io.github.hadyang.leetcode.offer;

import java.util.HashMap;
import org.junit.Test;

/** @author haoyang.shi */
public class LongestNoRepeatSubString {

  @Test
  public void test() {
    System.out.println(longestNoRepeatSubString("abcabcbb"));
    System.out.println(longestNoRepeatSubString("bbbbb"));
    System.out.println(longestNoRepeatSubString("pwwkew"));
    System.out.println(longestNoRepeatSubString("p"));
    System.out.println(longestNoRepeatSubString("abba"));
    System.out.println(longestNoRepeatSubString("tmmzuxt"));
  }

  public int longestNoRepeatSubString(String str) {
    if (str == null || str.length() == 0) return 0;

    HashMap<Character, Integer> temp = new HashMap<>();
    char[] chars = str.toCharArray();

    int res = 0, start = 0;
    for (int i = 0; i < chars.length; i++) {
      if (temp.containsKey(chars[i])) {
        start = Math.max(temp.put(chars[i], i) + 1, start);
      }

      temp.put(chars[i], i);
      res = Math.max(res, i - start + 1);
    }

    return res;
  }
}
